<template>
    <div class="grade-submission-container" v-loading="loading">
      <el-page-header @back="goBack" class="page-header">
        <template #content>
          <span class="text-large font-600 mr-3"> 批改学生答卷 </span>
        </template>
      </el-page-header>
  
      <el-card v-if="submissionDetail" class="submission-summary">
        <template #header>
          <div class="card-header">
            <span>答卷概览</span>
          </div>
        </template>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="答卷ID">{{ submissionDetail.examSubmission.id }}</el-descriptions-item>
          <el-descriptions-item label="学生ID">{{ submissionDetail.examSubmission.studentId }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ formatTime(submissionDetail.examSubmission.submitTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="考核ID">{{ submissionDetail.examSubmission.examId }}</el-descriptions-item>
          <el-descriptions-item label="批改状态">
            <el-tag :type="statusType(submissionDetail.examSubmission.gradingStatus)">
              {{ gradingStatusText(submissionDetail.examSubmission.gradingStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前总分">
            <span style="color: #409eff; font-weight: bold;">{{ currentTotalScore }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
  
      <div v-if="questionsWithAnswers.length > 0" class="question-list">
        <el-card v-for="(item, index) in questionsWithAnswers" :key="item.question.id" class="question-card">
          <template #header>
            <div class="card-header">
              <span>{{ index + 1 }}. {{ questionTypeText(item.question.questionType) }} ({{ item.question.points }}分)</span>
            </div>
          </template>
  
          <div class="question-content">
            <p v-html="item.question.content"></p>
          </div>
  
          <div v-if="isObjective(item.question.questionType)" class="options-section">
            <el-radio-group v-if="item.question.questionType === 'single_choice'" disabled>
              <el-radio v-for="option in item.examQuestionOptions" :key="option.id" :label="getOptionLabel(option.sequence)">
                {{ getOptionLabel(option.sequence) }}. {{ option.optionContent }}
              </el-radio>
            </el-radio-group>
            <el-checkbox-group v-if="item.question.questionType === 'multi_choice'" disabled>
              <el-checkbox v-for="option in item.examQuestionOptions" :key="option.id" :label="getOptionLabel(option.sequence)">
                 {{ getOptionLabel(option.sequence) }}. {{ option.optionContent }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
  
          <el-divider />
  
          <div class="answer-section">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="answer-block reference-answer">
                  <strong>参考答案：</strong>
                  <p>{{ item.question.referenceAnswer }}</p>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="answer-block student-answer">
                  <strong>学生答案：</strong>
                  <p>{{ item.examAnswer.content || '未作答' }}</p>
                </div>
              </el-col>
            </el-row>
          </div>
  
          <el-divider />
  
          <div class="grading-section">
              <strong>评分标准：</strong>
              <p>{{ item.question.scoringCriteria }}</p>
              <div class="score-input">
                  <strong>得分：</strong>
                  <el-input-number
                      v-if="!isObjective(item.question.questionType)"
                      v-model="item.examAnswer.score"
                      :min="0"
                      :max="item.question.points"
                      :step="0.5"
                      controls-position="right"
                      size="small"
                  />
                  <el-radio-group v-else v-model="item.examAnswer.score">
                      <el-radio :label="0">0分</el-radio>
                      <el-radio v-if="item.question.questionType === 'multi_choice'" :label="item.question.points / 2">
                          {{ item.question.points / 2 }}分 (部分正确)
                      </el-radio>
                      <el-radio :label="item.question.points">{{ item.question.points }}分 (完全正确)</el-radio>
                  </el-radio-group>
              </div>
          </div>
        </el-card>
      </div>
  
      <el-affix position="bottom" :offset="20">
          <div class="submit-footer">
              <el-button type="primary" size="large" @click="handleSubmitGrading" :loading="examStore.loading">
                  提交批改
              </el-button>
          </div>
      </el-affix>
  
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useExamStore } from '@/stores/exam.js'; // 确保路径正确
  import { ElMessage } from 'element-plus';
  import dayjs from 'dayjs';
  
  const route = useRoute();
  const router = useRouter();
  const examStore = useExamStore();
  
  const submissionDetail = ref(null);
  const questionsWithAnswers = ref([]);
  const loading = ref(false);
  
  const submissionId = route.params.submissionId;
  
  // 获取数据
  onMounted(async () => {
    console.log('submissionId:', submissionId);
    if (submissionId) {
      loading.value = true;
      await examStore.fetchSubmissionById(submissionId, (data) => {
        submissionDetail.value = data;
        // 深拷贝一份数据用于修改
        questionsWithAnswers.value = JSON.parse(JSON.stringify(data.examQuestionAnswerVos || []));
        loading.value = false;
      }, () => {
        loading.value = false;
      });
    }
  });
  
  // 计算当前总分
  const currentTotalScore = computed(() => {
      return questionsWithAnswers.value.reduce((sum, item) => {
          return sum + (Number(item.examAnswer.score) || 0);
      }, 0).toFixed(2);
  });
  
  // 提交批改
  const handleSubmitGrading = async () => {
      // 假设 teacherId 从当前登录用户状态中获取，这里硬编码为1
      const teacherId = 1; 
  
      const updateAnswerScoreDTOList = questionsWithAnswers.value.map(item => ({
          answerId: item.examAnswer.id,
          score: item.examAnswer.score
      }));
  
      const gradingData = {
          teacherId,
          updateAnswerScoreDTOList
      };
  
      await examStore.manualGradeSubmission(gradingData, () => {
          // 批改成功后可以刷新数据或返回上一页
          goBack();
      });
  };
  
  // 返回上一页
  const goBack = () => {
    router.back();
  };
  
  // 格式化时间
  const formatTime = (timeStr) => {
      return timeStr ? dayjs(timeStr).format('YYYY-MM-DD HH:mm:ss') : 'N/A';
  };
  
  // 题型文本转换
  const questionTypeText = (type) => {
      const map = {
          single_choice: '单选题',
          multi_choice: '多选题',
          fill_blank: '填空题',
          short_answer: '简答题'
      };
      return map[type] || '未知题型';
  };
  
  // 批改状态文本和样式
  const gradingStatusText = (status) => {
      const map = {
          pending: '待批改',
          grading: '批改中',
          completed: '已完成'
      };
      return map[status] || '未知';
  }
  const statusType = (status) => {
      const map = {
          pending: 'info',
          grading: 'warning',
          completed: 'success'
      };
      return map[status] || 'info';
  }
  
  // 判断是否为客观题
  const isObjective = (type) => {
      return ['single_choice', 'multi_choice'].includes(type);
  };
  
  // 获取选项标签（A, B, C...）
  const getOptionLabel = (sequence) => {
      return String.fromCharCode(64 + sequence);
  };
  
  </script>
  
  <style scoped>
  .grade-submission-container {
    padding: 20px;
    background-color: #f5f7fa;
  }
  
  .page-header {
    margin-bottom: 20px;
    background-color: #fff;
    padding: 16px 24px;
    border-radius: 4px;
  }
  
  .submission-summary {
    margin-bottom: 20px;
  }
  
  .question-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .question-content {
    margin-bottom: 15px;
    font-size: 16px;
    line-height: 1.6;
  }
  
  .options-section {
    margin-bottom: 15px;
  }
  
  .options-section .el-radio-group,
  .options-section .el-checkbox-group {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
  }
  
  .options-section .el-radio,
  .options-section .el-checkbox {
      margin-bottom: 8px;
  }
  
  
  .answer-section .answer-block {
      padding: 10px;
      border-radius: 4px;
      min-height: 80px;
  }
  
  .answer-section .reference-answer {
      background-color: #f0f9eb;
      border: 1px solid #e1f3d8;
  }
  
  .answer-section .student-answer {
      background-color: #fdf6ec;
      border: 1px solid #faecd8;
  }
  
  .answer-section strong {
      display: block;
      margin-bottom: 8px;
  }
  
  .answer-section p {
      margin: 0;
      white-space: pre-wrap; /* 保持换行 */
  }
  
  .grading-section {
      background-color: #f4f4f5;
      padding: 15px;
      border-radius: 4px;
      margin-top: 15px;
  }
  
  .grading-section strong {
      display: block;
      margin-bottom: 8px;
  }
  
  .grading-section p {
      margin: 0 0 15px 0;
      font-size: 14px;
      color: #909399;
  }
  
  .grading-section .score-input {
      display: flex;
      align-items: center;
      gap: 15px;
  }
  
  .submit-footer {
      display: flex;
      justify-content: center;
      padding: 10px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  }
  </style>